package com.boxedinsoftware.betamax.dial;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class CallHandler extends Activity {
	
	
	AccountsSQLHelper dh;
	ArrayList<SearchResults> searchResults;
	ListView lv1;
	ArrayList<SearchResults> results;
	String country;
	int choice;
	String phone;
	String sCountry;
	String sNumber;
	boolean fastCall = false;
	protected SharedPreferences preferences;
	boolean callBackDebugBoolean = false;
	
		@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.call_handler);
	        phone = this.getIntent().getStringExtra("number");
	        choice = this.getIntent().getIntExtra("choice", 0);
	        country = this.getIntent().getStringExtra("country");
	        sNumber = this.getIntent().getStringExtra("sNumber");
	        preferences = PreferenceManager.getDefaultSharedPreferences(this);
	        callBackDebugBoolean = preferences.getBoolean("callbackDebug", false);
	        fastCall = preferences.getBoolean("fastCall", false);
	        this.dh = new AccountsSQLHelper(CallHandler.this.getApplicationContext());
	       Button manage = (Button)findViewById(R.id.handler_manage_button);
	        manage.setOnClickListener(new OnClickListener(){

				public void onClick(View arg0) {
					Intent x = new Intent(CallHandler.this, AccountManager.class);
					startActivity(x);
					CallHandler.this.finish();

					
				}
	        	
	        	
	        });
	        if(choice == 1)
	        {
	        searchResults = refresh();
	        
	        lv1 = (ListView)this.findViewById(R.id.handler_list);
	        lv1.setAdapter(new CallBaseAdapter(this, searchResults));
	        lv1.setEmptyView((View)findViewById(android.R.id.empty));
	        if (dh.getCount() == 1 && fastCall == true)
	        {	
	        	try{
	          Object o = lv1.getItemAtPosition(0);
	          SearchResults fullObject = (SearchResults)o;
	  	        if(phone == "")
        	{
        		
        		Toast.makeText(getApplicationContext(), "Failed. No phone number provided.", Toast.LENGTH_LONG).show();
        		
        	}
        	else if(!phone.startsWith("+") && !phone.startsWith("00"))
        	{
        		
        		Toast.makeText(getApplicationContext(), "Failed. Phone number does not contain a country code. Eg. +16642295346 or 0016642295346", Toast.LENGTH_LONG).show();
        		
        	}
        	else
        	{
        	if(phone.startsWith("+"))
        	{
        		phone = phone.replace('+', '0');
        		phone = "0" + phone;
        	}
        	Uri uri = Uri.parse("tel:" + fullObject.getAccNumber()+"%2C" +phone+"%23");
        	//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
     	   Intent intent = new Intent(Intent.ACTION_CALL);
     	   intent.setData(uri);
     	   startActivity(intent);
     	   CallHandler.this.finish();
        	}
	        	}catch(Exception e){}
	  	    }
	        else
	        	get_rates_refresh();
	        lv1.setEmptyView(findViewById(android.R.id.empty));
	        
	        lv1.setOnItemClickListener(new OnItemClickListener(){

	        	public void onItemClick(AdapterView<?> a, View v, int position, long id) { 
	  	          Object o = lv1.getItemAtPosition(position);
	  	          SearchResults fullObject = (SearchResults)o;
	  	        if(phone == "")
            	{
            		
            		Toast.makeText(getApplicationContext(), "Failed. No phone number provided.", Toast.LENGTH_LONG).show();
            		
            	}
            	else if(!phone.startsWith("+") && !phone.startsWith("00"))
            	{
            		
            		Toast.makeText(getApplicationContext(), "Failed. Phone number does not contain a country code. Eg. +16642295346 or 0016642295346", Toast.LENGTH_LONG).show();
            		
            	}
            	else
            	{
            	if(phone.startsWith("+"))
            	{
            		phone = phone.replace('+', '0');
            		phone = "0" + phone;
            	}
            	Uri uri = Uri.parse("tel:" + fullObject.getAccNumber()+"%2C" +phone+"%23");
            	//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
         	   Intent intent = new Intent(Intent.ACTION_CALL);
         	   intent.setData(uri);
         	   startActivity(intent);
         	   CallHandler.this.finish();
            	}
	  			  
	  	          
	  	         }  
	  	        });
	        
	        
	        
	        }
	        else if(choice == 2)
	        {
	        	sCountry = this.getIntent().getStringExtra("sCountry");
	        	Log.e("Betamax", sCountry);
	        	searchResults = refresh();
	 	        
	 	        lv1 = (ListView)this.findViewById(R.id.handler_list);
	 	        
	 	        lv1.setAdapter(new CallBaseAdapter(this, searchResults));
	 	        lv1.setEmptyView(findViewById(android.R.id.empty));
	 	        if(dh.getCount()== 1 && fastCall == true)
	 	        {
	 	        	try{
	 	        	 Object o = lv1.getItemAtPosition(0);
		  	          SearchResults fullObject = (SearchResults)o;
		  	        if(phone == "")
	            	{
	            		
	            		Toast.makeText(getApplicationContext(), "Failed. No phone number provided.", Toast.LENGTH_LONG).show();
	            		
	            	}
	            	else if(!phone.startsWith("+") && !phone.startsWith("00"))
	            	{
	            		
	            		Toast.makeText(getApplicationContext(), "Failed. Phone number does not contain a country code. Eg. +16642295346 or 0016642295346", Toast.LENGTH_LONG).show();
	            		
	            	}
	            	else
	            	{
	            		
	            		String[] params = {fullObject.getProvider() , fullObject.getUsername() , fullObject.getPassword(), phone, sNumber};
	            		//Toast.makeText(getApplicationContext(), fullObject.getPassword(), Toast.LENGTH_LONG).show();
	            		new callBack().execute(params);
	            		
	            	}
	            	
	 	        	}
	 	        	catch(Exception e){}
	         	   
	            	}
		  			  
	 	        else{     
		  	           
		  	        
	 	        
	 	        lv1.setOnItemClickListener(new OnItemClickListener(){

		        	public void onItemClick(AdapterView<?> a, View v, int position, long id) { 
		  	          Object o = lv1.getItemAtPosition(position);
		  	          SearchResults fullObject = (SearchResults)o;
		  	        if(phone == "")
	            	{
	            		
	            		Toast.makeText(getApplicationContext(), "Failed. No phone number provided.", Toast.LENGTH_LONG).show();
	            		
	            	}
	            	else if(!phone.startsWith("+") && !phone.startsWith("00"))
	            	{
	            		
	            		Toast.makeText(getApplicationContext(), "Failed. Phone number does not contain a country code. Eg. +16642295346 or 0016642295346", Toast.LENGTH_LONG).show();
	            		
	            	}
	            	else
	            	{
	            		
	            		String[] params = {fullObject.getProvider() , fullObject.getUsername() , fullObject.getPassword(), phone, sNumber};
	            		//Toast.makeText(getApplicationContext(), fullObject.getPassword(), Toast.LENGTH_LONG).show();
	            		new callBack().execute(params);
	            		
	            	}
	            	
	            	
	         	   
	            	}
		  			  
		  	          
		  	           
		  	        });
	 	        
	 	       get_callback_rates_refresh();}
	        }
	        
	        //Toast.makeText(this, "number : " + phone + " - choice : " + choice, Toast.LENGTH_LONG).show();
	        
	        
	        
	        
		}
		
		
		private ArrayList<SearchResults> refresh(){
		     ArrayList<SearchResults> results = new ArrayList<SearchResults>();
		     
		     SearchResults sr1;
		     Cursor cursor = this.dh.selectAllForCall();
		        while (cursor.moveToNext()) {
		        	sr1 = new SearchResults();
		            sr1.setID(cursor.getInt(0));
		            sr1.setProvider(cursor.getString(1));
		            sr1.setUsername(cursor.getString(2));
		            sr1.setPassword(cursor.getString(3));
		            sr1.setAccNumber(cursor.getString(4));
		            sr1.setBalance(cursor.getDouble(5));
		            if((sr1.getAccNumber().length() > 5) == true || choice == 2)
		            	results.add(sr1);
		          }
		         
		     return results;
		    }
		
		private void get_rates_refresh(){
		     searchResults = new ArrayList<SearchResults>();
		     
		     SearchResults sr1;
		     Cursor cursor = this.dh.selectAllForCall();
		        while (cursor.moveToNext()) {
		        	sr1 = new SearchResults();
		            sr1.setID(cursor.getInt(0));
		            sr1.setProvider(cursor.getString(1));
		            sr1.setUsername(cursor.getString(2));
		            sr1.setPassword(cursor.getString(3));
		            sr1.setAccNumber(cursor.getString(4));
		            sr1.setBalance(cursor.getDouble(5));
		            //Log.e("Betamax", "" + sr1.getAccNumber());
		            SearchResults[] vasile = {sr1};
		            if((sr1.getAccNumber().length() > 5) == true)
		            	new get_rates().execute(vasile);
		          }
		         
		        cursor.close();
		     
		    }
		
		private void get_callback_rates_refresh(){
		     searchResults = new ArrayList<SearchResults>();
		     
		     SearchResults sr1;
		     Cursor cursor = this.dh.selectAllForCall();
		        while (cursor.moveToNext()) {
		        	sr1 = new SearchResults();
		        	sr1.setCallback(true);
		            sr1.setID(cursor.getInt(0));
		            sr1.setProvider(cursor.getString(1));
		            sr1.setUsername(cursor.getString(2));
		            sr1.setPassword(cursor.getString(3));
		            sr1.setAccNumber(cursor.getString(4));
		            sr1.setBalance(cursor.getDouble(5));
		            //Log.e("Betamax", "" + sr1.getAccNumber());
		            SearchResults[] vasile = {sr1};
		            if(!(sr1.getProvider().equalsIgnoreCase("megavoip.com") ||
		            		sr1.getProvider().equalsIgnoreCase("voipian.com") ||
		            		sr1.getProvider().equalsIgnoreCase("dialcheap.com")))
		            	new get_callback_rates().execute(vasile);
		          }
		         
		        cursor.close();
		     
		    }
		
		
		
		public class get_rates extends AsyncTask<SearchResults, Void, String> {
	    	
	    	SearchResults[] params;
	    	
	    	@Override
	    	protected String doInBackground(SearchResults... params) {
	    		try{
	        		
	        		this.params = params;
					//Log.e("providerString", providerString);
					
					//Log.e("actualProvider", actualProvider);
	        		 //Log.e("Betamax", this.params[0].getProvider());
				    HttpClient httpclient = new DefaultHttpClient();  
				    HttpGet httpget = new HttpGet("http://www.boxedinsoftware.com/betamax/dialer/getRates.php?country="+country.replaceAll(" ", "%20")+"&provider="+this.params[0].getProvider());
		            // Add your data  
		           
		      
		            // Execute HTTP Post Request  
		            HttpResponse response = httpclient.execute(httpget);  
		            
		            byte buffer[] = new byte[1024] ;
					InputStream is = response.getEntity().getContent() ;
					int numBytes = is.read(buffer) ;
					is.close();
					
					 String entityContents = new String(buffer,0,numBytes) ;
				    
						

						
			            
					 return entityContents;   
					}      
		         catch (ClientProtocolException e) { 
		        	Log.e("Betamax" , e.getMessage());
		        	return null; 
		        } catch (IOException e) {  
		        	Log.e("Betamax" , e.getMessage());
		        	return null; 
		        }
		        
	    	
	    	
	    	
	 }
	    	
	    	@Override
	    	protected void onPostExecute(String result) {
	    	
	    		if(result == null){
	    			Toast.makeText(CallHandler.this, "Something went wrong. Please check your internet connection", Toast.LENGTH_SHORT).show();
	    			String landline = "-1";
		    		String mobile = "-1";
		    		params[0].setLandline(Double.parseDouble(landline));
		    		params[0].setMobile(Double.parseDouble(mobile));
		    		searchResults.add(params[0]);
					lv1.setAdapter(new CallBaseAdapter(CallHandler.this, searchResults));
	    		}
	    		else if(result.startsWith("Unknown"))
	    		{
	    			Toast.makeText(CallHandler.this, "Unable to fetch rates for " + params[0].getProvider(), Toast.LENGTH_SHORT).show();
	    			String landline = "-1";
		    		String mobile = "-1";
		    		params[0].setLandline(Double.parseDouble(landline));
		    		params[0].setMobile(Double.parseDouble(mobile));
		    		searchResults.add(params[0]);
					lv1.setAdapter(new CallBaseAdapter(CallHandler.this, searchResults));
	    		}
	    		else{
	    			//Log.e("Betamax", result);
	    			String[] rates = result.split("\\|");
		    		String landline = "";
		    		try{
		    		landline = rates[0];}
		    		catch(Exception e){landline = "-1";}
		    		String mobile = "";
		    		try{
		    		mobile = rates[1];
		    		}catch(Exception e){mobile = "-1";}
		    		//Log.e("Betamax", "---" + mobile + "---- " + landline);
		    		try{
		    		params[0].setLandline(Double.parseDouble(landline));}
		    		catch(Exception e){params[0].setLandline(-1);}
		    		try{
		    		params[0].setMobile(Double.parseDouble(mobile));}
		    		catch(Exception e){params[0].setMobile(-1);}
	    		searchResults.add(params[0]);
				lv1.setAdapter(new CallBaseAdapter(CallHandler.this, searchResults));
	    		}
	    	}
	    	
	 }
		
		
public class get_callback_rates extends AsyncTask<SearchResults, Void, String> {
	    	
	    	SearchResults[] params;
	    	
	    	@Override
	    	protected String doInBackground(SearchResults... params) {
	    		try{
	        		
	        		this.params = params;
					//Log.e("providerString", providerString);
					
					//Log.e("actualProvider", actualProvider);
	        		 //Log.e("Betamax", this.params[0].getProvider());
				    HttpClient httpclient = new DefaultHttpClient();  
				    HttpGet httpget = new HttpGet("http://www.boxedinsoftware.com/betamax/dialer/getCallbackRates.php?country="+country.replaceAll(" ", "%20")+"&provider="+this.params[0].getProvider()+"&sCountry="+sCountry.replaceAll(" ", "%20"));
		            // Add your data  
				    
				    //Log.e("Betamax", httpget.getURI().toURL().toString());
		           
		      
		            // Execute HTTP Post Request  
		            HttpResponse response = httpclient.execute(httpget);  
		            
		            byte buffer[] = new byte[2048] ;
					InputStream is = response.getEntity().getContent() ;
					int numBytes = is.read(buffer) ;
					is.close();
					
					 String entityContents = new String(buffer,0,numBytes) ;
				    
						

						
			            
					 return entityContents;   
					}      
		         catch (ClientProtocolException e) { 
		        	Log.e("Betamax" , e.getMessage());
		        	return null; 
		        } catch (IOException e) {  
		        	Log.e("Betamax" , e.getMessage());
		        	return null; 
		        }
		        
	    	
	    	
	    	
	 }
	    	
	    	@Override
	    	protected void onPostExecute(String result) {
	    	
	    		if(result == null){
	    			Toast.makeText(CallHandler.this, "Something went wrong. Please check your internet connection", Toast.LENGTH_SHORT).show();
	    			String landline = "-1";
		    		String mobile = "-1";
		    		params[0].setLandline(Double.parseDouble(landline));
		    		params[0].setMobile(Double.parseDouble(mobile));
		    		searchResults.add(params[0]);
					lv1.setAdapter(new CallBaseAdapter(CallHandler.this, searchResults));
	    		}
	    		else if(result.startsWith("Unknown"))
	    		{
	    			Toast.makeText(CallHandler.this, "Unable to fetch rates for " + params[0].getProvider(), Toast.LENGTH_SHORT).show();
	    			String landline = "-1";
		    		String mobile = "-1";
		    		params[0].setLandline(Double.parseDouble(landline));
		    		params[0].setMobile(Double.parseDouble(mobile));
		    		searchResults.add(params[0]);
					lv1.setAdapter(new CallBaseAdapter(CallHandler.this, searchResults));
	    		}
	    		else{
	    		//Log.e("Betamax", result);
	    		String[] rates = result.split("\\|");
	    		String landline = "";
	    		try{
	    		landline = rates[0];}
	    		catch(Exception e){landline = "-1";}
	    		String mobile = "";
	    		try{
	    		mobile = rates[1];
	    		}catch(Exception e){mobile = "-1";}
	    		//Log.e("Betamax", "---" + mobile + "---- " + landline);
	    		try{
	    		params[0].setLandline(Double.parseDouble(landline));
	    		}catch(Exception e){params[0].setLandline(-1);}
	    		try{
	    		params[0].setMobile(Double.parseDouble(mobile));
	    		}catch(Exception e){params[0].setMobile(-1);}
	    		searchResults.add(params[0]);
	    		
				lv1.setAdapter(new CallBaseAdapter(CallHandler.this, searchResults));
	    		}
	    	}
	    	
	 }

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		this.dh.stop();
		
	}
	
	
	public class callBack extends AsyncTask<String, Void, String> {
    	final ProgressDialog progress = ProgressDialog.show(CallHandler.this,    
                "Requesting CallBack ... ", "Please wait ... You will receive a Private Call after this dialog closes.", true);
    	
    	protected String[] params;
    	
    	@Override
    	protected String doInBackground(String... params) {
    		try{
        		this.params = params;
        		
				callBackDebugBoolean = preferences.getBoolean("callbackDebug", false);
				
				String number = params[3];
				String sourceNumberString = params[4];
				
				/*if(number.startsWith("+"))
				{
					
					number = number.replace('+', '0');
					number = "0" + number;
					
				}*/
		
				/*if(sourceNumberString.startsWith("+"))
				{
					
					sourceNumberString = sourceNumberString.replace('+', '0');
					sourceNumberString = "0" + sourceNumberString;
					
				}*/
				
				if(sourceNumberString.equalsIgnoreCase(""))
				{
					TelephonyManager tMgr =(TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
					sourceNumberString= tMgr.getLine1Number();
					
				}
				
				number = number.replaceAll( "-", "" );
                number = number.replace(")", "");
                number = number.replace("(", "");
                number = number.replaceAll(" ", "");
                number = number.replaceAll("[a-z,A-Z]", "");
				
				//Log.e("providerString", providerString);
				
			    HttpClient httpclient = new DefaultHttpClient();  
		        //HttpGet httpget = new HttpGet("http://www.aldeaglobal.net/callserver/call.php?provider="+params[0]+"&us="+params[1].trim()+"&ps="+params[2].trim()+"&tela="+sourceNumberString+"&telb="+number);
			    HttpGet httpget = new HttpGet("https://www."+params[0]+"/myaccount/makecall.php?username="+params[1].trim()+"&password="+params[2].trim()+"&from="+sourceNumberString+"&to="+number);
			    //Log.e("URL", httpget.getURI().toString());
	            // Add your data  
	            
	      
	            // Execute HTTP Post Request  
	            HttpResponse response = httpclient.execute(httpget);  
	            
	            byte buffer[] = new byte[1024] ;
				InputStream is = response.getEntity().getContent() ;
				int numBytes = is.read(buffer) ;
				is.close();
				
				 String entityContents = new String(buffer,0,numBytes) ;
			    
					

					
		            
				 return entityContents;   
				
				
				
				
		            
		           
		            
	            
	            
	            
	            
	              
	        } catch (ClientProtocolException e) {  
	        	
	        	return e.getMessage();
	        } catch (IOException e) {  
	        	
	        	return e.getMessage();
	        	
	        }
	        
	       
    	}

    	/* (non-Javadoc)
    	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
    	 */
    	@Override
    	protected void onPostExecute(String result) {
    		
            progress.dismiss();
            //Log.e("Betamax Callback", result);
            
            
            
        	 
    		
    		super.onPostExecute(result);
    		
    		if(callBackDebugBoolean == true)
            	displayDebug(result , params[0]);
    		else
    		    CallHandler.this.finish();
    	}

    	/* (non-Javadoc)
    	 * @see android.os.AsyncTask#onPreExecute()
    	 */
    	@Override
    	protected void onPreExecute() {
    		// TODO Auto-generated method stub
    		super.onPreExecute();
    	}

    	/* (non-Javadoc)
    	 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
    	 */
    	@Override
    	protected void onProgressUpdate(Void... values) {
    		// TODO Auto-generated method stub
    		super.onProgressUpdate(values);
    	}

    }
	
	public void displayDebug(final String message , final String provider)
    {
    	ComponentName comp = new ComponentName(this,dialNow.class);
        PackageInfo pinfo = null;
		try {
			pinfo = CallHandler.this.getPackageManager().getPackageInfo(comp.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	final String firmwareVersion = Build.VERSION.RELEASE;
    	final String model = Build.MODEL;
    	final String display = Build.DISPLAY;
    	final String appVersion = pinfo.versionName;
    	final int appCode = pinfo.versionCode;
    	final String actualProvider = provider;
    	
    	
    	
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("Debug Dialog")
    	       .setMessage("Firmware : " + firmwareVersion + "\n" +
    	    		   	   "Phone Model : " + model + "\n" +
    	    		   	   "ROM : " + display + "\n" +
    	    		   	   "App Version : " + appVersion + "\n" +
    	    		   	   "App Code : " + appCode + "\n" +
    	    		   	   "BetaMax Provider : " +  actualProvider + "\n\n\n" + 
    	    		   	   "DEBUG MESSAGE STARTS HERE\n" +
    	    		   	   "-------------------------------------------\n" + 
    	    		   	   message+
    	    		   	   "\n-------------------------------------------")
    	       .setCancelable(false)
    	       .setNegativeButton("OK", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	    CallHandler.this.finish();
    	                dialog.cancel();
    	           }
    	       })
    	       .setPositiveButton("Send To Dev", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                       
                       emailIntent.setType("plain/text");
                  
                       emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "support@boxedinsoftware.com"});
                
                       emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "[DEBUG BetaMax Dialer Pro v" + appVersion +"]");
                
                       emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, 
                    		   "\n\n\n-------------------------------------------\n" +
                       		   "Firmware : " + firmwareVersion + "\n" +
        	    		   	   "Phone Model : " + model + "\n" +
        	    		   	   "ROM : " + display + "\n" +
        	    		   	   "App Version : " + appVersion + "\n" +
        	    		   	   "App Code : " + appCode + "\n" + 
        	    		   	   "BetaMax Provider : " + actualProvider + "\n\n\n" +
        	    		   	   "DEBUG MESSAGE STARTS HERE\n" +
        	    		   	   "-------------------------------------------\n" + 
        	    		   	   message+
        	    		   	   "\n-------------------------------------------");
        
                       CallHandler.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
                       CallHandler.this.finish();
                       dialog.cancel();
    	           }
    	       });
    	AlertDialog alert = builder.create();
    	alert.show();
        
        
        
    }
	
}